package cn.wolfcode.mq;

import cn.wolfcode.common.domain.UserInfo;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 订单消息监听 (MQConstant.ORDER_PEDDING_TOPIC 队列的消费者)
 */
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_PEDDING_TOPIC,
        consumerGroup = MQConstant.ORDER_PEDDING_TOPIC + "_CUSTOMER_GROUP"
)
public class MQOrderListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService  orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMessage orderMessage) {
        System.out.println("=============到了订单的消费者中==============");

        SeckillProductVo seckillProductVo = orderMessage.getSeckillProductVo();
        UserInfo userInfo = orderMessage.getUserInfo();


        // 再次封装消息, 接下来发送给订单结果队列
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setTime(seckillProductVo.getTime());
        orderMQResult.setSeckillId(seckillProductVo.getId());
        orderMQResult.setToken(orderMessage.getToken());

        String tag = "";
        try{
            // 下单成功: time, seckillId, token, orderNo
            String orderNo = orderInfoService.doSeckill(seckillProductVo, userInfo);
            orderMQResult.setOrderNo(orderNo);
            tag = MQConstant.ORDER_RESULT_SUCCESS_TAG;

            // 发送一个延迟消息, 如果未支付就恢复库存
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC, MessageBuilder.withPayload(orderMQResult).build()
                    , 1000
//                    , MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
                    , 13);

        } catch (Exception e){
            // 下单失败: time, seckillId, token, code, msg
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            tag = MQConstant.ORDER_RESULT_FAIL_TAG;
            e.printStackTrace();
        }

        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC + ":" + tag, orderMQResult);

    }
}
